package com.sanploy.server.websocket;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by 1 on 2017/8/28.
 */
@Service
public class MySocketHandler implements WebSocketHandler{

    private Gson gson = new Gson();
    private  ConcurrentHashMap<Long, Integer> map = new ConcurrentHashMap<Long, Integer>();
    private  final Logger logger = LoggerFactory.getLogger(MySocketHandler.class);
    private  final ConcurrentHashMap<String, WebSocketSession> users = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if (putSession(session)){
            session.sendMessage(new TextMessage("successful"));
        }else {
            session.sendMessage(new TextMessage("fail"));
        }
        logger.info(session.getUri()+" afterConnectionEstablished");
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        logger.info(session.getUri()+" handleMessage");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        logger.info(session.getUri()+" handleTransportError");

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info(session.getUri()+" afterConnectionClosed");
        distorySession(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        logger.info("supportsPartialMessages");
        return false;
    }

    /**
     * 建立连接时获取设备名
     * @param session
     * @return
     */
    private String getSessionName(WebSocketSession session){
        String[] nameArr = session.getUri().getQuery().split("=");
        if (nameArr.length==2){
            if (nameArr[0].equals("name")){
                return nameArr[1];
            }
        }
        return null;
    }

    private boolean putSession(WebSocketSession session){
        String name = getSessionName(session);
        if (name != null){
            users.put(name,session);
            return true;
        }else {
            return false;
        }
    }

    private boolean distorySession(WebSocketSession session){
        String name = getSessionName(session);
        if (name != null){
            users.remove(name);
            return true;
        }else {
            return false;
        }
    }

    public boolean pushSuccessful(String name,String nickName){
        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setNickName(nickName);
        socketMsg.setTime(String.valueOf(System.currentTimeMillis()));
        try {
            users.get(name).sendMessage(new TextMessage(gson.toJson(socketMsg)));
            return true;
        } catch (IOException e) {
            logger.info("send fail!!!!");
            e.printStackTrace();
        }
        return false;
    }



}
